<template>
  <Modal v-model="modelIsOpen" width="650" mask :closable="false">
    <template #footer>
      <Button size="default" @click="cancel('close')" :loading="btnLoading"
        >取消</Button
      >
      <Button
        v-if="currentStep !== 0"
        size="default"
        @click="preStep"
        :loading="btnLoading"
        >上一步</Button
      >
      <Button
        v-if="currentStep !== 2"
        type="primary"
        size="default"
        @click="nextStep"
        :loading="btnLoading"
        >下一步</Button
      >
      <Button
        v-if="currentStep === 2"
        type="primary"
        size="default"
        :loading="btnLoading"
        @click="ok"
        >确定</Button
      >
    </template>
    <Space direction="vertical" size="default" type="flex">
      <zz-Label text="新增用户"></zz-Label>
      <Steps :current="currentStep" size="small">
        <Step title="用户快照"></Step>
        <Step title="系统配置"></Step>
        <Step title="账号绑定"></Step>
      </Steps>
      <template v-if="currentStep === 0">
        <div class="container" ref="container" @scroll="scrollToTop">
          <Space direction="vertical" size="default" type="flex">
            <zz-Form
              ref="zzForm1"
              title="基本信息"
              :model="model"
              :rules="ruleValidate"
              key="1"
            >
              <Col span="24">
                <FormItem
                  label="上传头像"
                  style="display: flex; align-items: center"
                >
                  <Upload
                    ref="upload"
                    name="avatar"
                    type="drag"
                    :default-file-list="defaultList"
                    :action="'api/user/upload-ava'"
                    :format="['jpg', 'jpeg', 'png']"
                    accept=".jpg,.jpeg,.png"
                    :show-upload-list="false"
                    :max-size="2048"
                    style="
                      display: inline-block;
                      width: 58px;
                      margin-left: -80px;
                    "
                    :on-success="handleSuccess"
                    :before-upload="handleBeforeUpload"
                    v-show="!ava.previewUrl"
                  >
                    <div style="width: 58px; height: 58px; line-height: 58px">
                      <Icon type="ios-camera" size="20"></Icon>
                    </div>
                  </Upload>
                  <div class="demo-upload-list" v-show="ava.previewUrl">
                    <template v-if="avalStatus === 'finished'">
                      <Image
                        :src="ava.previewUrl"
                        fit="cover"
                        width="100%"
                        height="100%"
                      />
                      <div class="demo-upload-list-cover">
                        <Icon type="ios-eye-outline" @click="handleView"></Icon>
                        <Icon
                          type="ios-trash-outline"
                          @click="handleRemove"
                        ></Icon>
                      </div>
                    </template>
                    <template v-else>
                      <Progress :percent="avalPercent" hide-info></Progress>
                    </template>
                  </div>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="用户编码" prop="userCode">
                  <Input
                    v-model="model.userCode"
                    placeholder="请输入..."
                    clearable
                    @on-blur="changeUserCode"
                  ></Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="性别" prop="sex">
                  <RadioGroup v-model="model.sex">
                    <Radio label="1">
                      <Image
                        src="src/assets/png/man.png"
                        fit="fit"
                        width="18px"
                        height="18px"
                      />
                      <span>男</span>
                    </Radio>
                    <Radio label="0">
                      <Image
                        src="src/assets/png/woman.png"
                        fit="fit"
                        width="18px"
                        height="18px"
                      />
                      <span>女</span>
                    </Radio>
                  </RadioGroup>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="用户姓名" prop="userName">
                  <Input
                    v-model="model.userName"
                    placeholder="请输入..."
                  ></Input>
                </FormItem>
              </Col>

              <Col span="12">
                <FormItem label="身份证号" prop="idNumber">
                  <Input
                    v-model="model.idNumber"
                    placeholder="请输入..."
                    @on-blur="changeIdNumber"
                    @on-clear="clearIdNumber"
                    clearable
                  ></Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="出生年月">
                  <DatePicker
                    type="date"
                    v-model="model.birthDay"
                    placeholder="请选择..."
                    transfer
                    @on-change="changeBirthDay"
                  />
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="年龄">
                  <Input
                    v-model="model.age"
                    number
                    placeholder="请输入..."
                  ></Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="手机号" prop="telephone">
                  <Input
                    v-model="model.telephone"
                    placeholder="请输入..."
                    @on-change="changeTelephone"
                    clearable
                  ></Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="邮箱" prop="email">
                  <Input v-model="model.email" placeholder="请输入..."></Input>
                </FormItem>
              </Col>
              <Col span="24">
                <FormItem label="地址">
                  <Input
                    v-model="model.address"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 5 }"
                    placeholder="请输入..."
                  ></Input>
                </FormItem>
              </Col>
            </zz-Form>
            <p v-if="showScrollHint" class="scroll-hint">下滑填写更多...</p>
            <zz-Form
              ref="zzForm2"
              title="教育信息"
              :model="model"
              :rules="ruleValidate"
              key="2"
            >
              <Col span="12">
                <FormItem label="毕业院校">
                  <Input v-model="model.school" placeholder="请输入..."></Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="学历">
                  <Input
                    v-model="model.education"
                    placeholder="请输入..."
                  ></Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="专业">
                  <Input v-model="model.major" placeholder="请输入..."></Input>
                </FormItem>
              </Col>
            </zz-Form>
            <zz-Form title="组织信息" key="3">
              <Col span="12">
                <FormItem label="公司">
                  <Select v-model="model.companyCode" transfer clearable>
                    <Option
                      v-for="item in companyList"
                      :value="item.companyCode"
                      :key="item.companyCode"
                    >
                      {{ item.companyName }}
                    </Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="部门">
                  <Input
                    v-model="model.departmentName"
                    placeholder="请输入..."
                  ></Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="职务">
                  <Input
                    v-model="model.jobPost"
                    placeholder="请输入..."
                  ></Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="职称">
                  <Input
                    v-model="model.jobTitle"
                    placeholder="请输入..."
                  ></Input>
                </FormItem>
              </Col>
            </zz-Form>
          </Space>
        </div>
      </template>
      <template v-if="currentStep === 1">
        <div class="container" ref="container" @scroll="scrollToTop">
          <Space direction="vertical" size="default" type="flex">
            <zz-Form
              ref="zzForm4"
              title="系统配置"
              :model="model"
              :rules="ruleValidate"
            >
              <Col span="12">
                <FormItem label="角色" prop="roleIds">
                  <TreeSelect
                    v-model="roleIds"
                    multiple
                    :data="roleTree"
                    show-checkbox
                    @on-change="changeRole"
                  />
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="使用系统">
                  <Switch v-model="useSys" @on-change="changeUseSys" />
                </FormItem>
              </Col>
              <Col span="24">
                <FormItem label="菜单权限">
                  <Input
                    v-model="model.menuRight"
                    placeholder="请输入..."
                    disabled
                  ></Input>
                </FormItem>
              </Col>
              <Col span="24">
                <FormItem label="数据权限">
                  <Input
                    v-model="model.dataRight"
                    placeholder="请输入..."
                    disabled
                  ></Input>
                </FormItem>
              </Col>
              <Col span="24">
                <FormItem label="首页挂件">
                  <Input
                    v-model="model.pendant"
                    placeholder="请输入..."
                    disabled
                  ></Input>
                </FormItem>
              </Col>
              <Col span="12" v-if="useSys">
                <FormItem label="登录账号" prop="loginAccount">
                  <Input
                    v-model="model.loginAccount"
                    placeholder="请输入..."
                  ></Input>
                </FormItem>
              </Col>

              <Col span="12" v-if="useSys">
                <FormItem label="登录密码">
                  <Row>
                    <Col span="16">
                      <Input
                        v-model="model.passWord"
                        placeholder="默认为初始密码..."
                        :disabled="passWordDisabled"
                        type="password"
                        password
                        @on-blur="changePassword"
                      ></Input>
                    </Col>
                    <Col span="4" class="ml-5">
                      <Button
                        @click="() => (passWordDisabled = !passWordDisabled)"
                        type="text"
                        style="font-size: 13px"
                        ><a>修改</a>
                      </Button>
                    </Col>
                    <Col span="2" class="ml-10">
                      <Icon type="ios-information-circle" />
                    </Col>
                  </Row>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="失效时间" prop="failureTime">
                  <DatePicker
                    type="date"
                    v-model="model.failureTime"
                    placeholder="请选择..."
                    transfer
                  />
                </FormItem>
              </Col>
            </zz-Form>
          </Space>
        </div>
      </template>
      <template v-if="currentStep === 2">
        <div class="container" ref="container" @scroll="scrollToTop">
          <Space direction="vertical" size="default" type="flex">
            <Alert show-icon>
              <template #icon>
                <Icon type="ios-bulb-outline"></Icon>
              </template>
              <template #desc
                >你可以绑定以下第三方帐号用于登录 zz-Admin
              </template>
            </Alert>
            <Row class="ivu-text-center">
              <template v-for="fit in fitList" :key="fit">
                <Col class="ml-40">
                  <Image
                    class="blur-image"
                    :src="fit.url"
                    fit="fit"
                    width="30px"
                    height="30px"
                    alt="fit"
                  />
                  <Paragraph class="ivu-mt">{{ fit.title }}</Paragraph>
                </Col>
              </template>
            </Row>
          </Space>
        </div>
      </template>
    </Space>
    <ImagePreview v-model="previewVisible" :preview-list="[ava.previewUrl]" />
  </Modal>
</template>

<script>
export default {
  name: 'addUser',
  emits: ['query'],
  watch: {
    modelIsOpen: {
      async handler(newVal) {
        if (newVal) {
          this.init()
        }
      },
      immediate: false,
    },
  },
  data() {
    return {
      modelIsOpen: false,
      loading: false,
      btnLoading: false,
      passWordDisabled: true,
      showScrollHint: true,
      useSys: true,
      currentStep: 0,
      model: {
        userCode: '',
        sex: '',
        userName: '',
        idNumber: '',
        birthDay: '',
        age: '',
        telephone: '',
        email: '',
        address: '',
        school: '',
        education: '',
        major: '',
        companyCode: '',
        departmentName: '',
        jobPost: '',
        jobTitle: '',
        role: '',
        menuRight: '',
        dataRight: '',
        pendant: '',
        loginAccount: '',
        passWord: '',
        failureTime: new Date('9999-12-31'),
      },
      fitList: [
        { url: 'src/assets/png/wechat.png', title: '微信' },
        { url: 'src/assets/png/qq.png', title: 'QQ' },
        { url: 'src/assets/png/weibo.png', title: '微博' },
        { url: 'src/assets/png/feishu.png', title: '飞书' },
        { url: 'src/assets/png/email.png', title: '邮箱' },
      ],
      // 头像文件
      ava: {
        previewUrl: '',
        externalUrl: '',
        fileName: '',
        minioFileName: '',
      },
      // 头像上传状态
      avalStatus: '',
      // 头像上传进度
      avalPercent: 0,
      defaultList: [],
      previewVisible: false,
      companyList: [],
      roleTree: [],
      roleIds: [],
      ruleValidate: {
        userCode: [
          {
            required: true,
            message: '用户编码不能为空...',
            trigger: 'change',
          },
        ],
        sex: [
          {
            required: true,
            message: '性别不能为空...',
            trigger: 'change',
          },
        ],
        userName: [
          { required: true, message: '用户姓名不能为空...', trigger: 'change' },
        ],
        telephone: [
          {
            pattern: /^1[34578]\d{9}$/,
            message: '手机号码格式不正确',
            trigger: 'blur',
          },
        ],
        email: [
          {
            pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
            message: '邮箱格式不正确',
            trigger: 'blur',
          },
        ],
        idNumber: [
          {
            pattern:
              /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$|^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$/,
            message: '身份证号码格式不正确',
            trigger: 'blur',
          },
        ],
        loginAccount: [
          {
            required: true,
            message: '登录账号不能为空...',
            trigger: 'change',
          },
        ],
        failureTime: [
          {
            required: true,
            type: 'date',
            message: '失效时间不能为空...',
            trigger: 'change',
          },
        ],
      },
    }
  },
  methods: {
    // 初始化
    async init() {
      this.companyList = [
        { companyCode: 'dhc', companyName: '信华信技术股份有限公司' },
        { companyCode: 'huawei', companyName: '华为股份有限公司' },
      ]
      await this.getRoleTree()
    },
    // 得到角色树
    async getRoleTree() {
      let res = await this.$API.roleManagement.role.queryAllWithRight.get()
      if (res.code === '01') {
        // 将列表转成树
        res.data.forEach((e) => {
          e.title = e.roleName
          e.selected = false
          e.checked = false
        })
        this.roleTree = this.$XEUtils.toArrayTree(res.data, {
          key: 'roleId',
        })
      }
    },
    // 下一步
    async nextStep() {
      // 表单校验
      let valid = true
      if (this.currentStep === 0) {
        valid = await this.$refs.zzForm1.validate()
      } else {
        valid = await this.$refs.zzForm4.validate()
      }

      if (!valid) {
        return
      }
      if (this.currentStep === 0) {
        this.currentStep = 1
      } else if (this.currentStep === 1) {
        if (this.useSys && this.roleIds.length <= 0) {
          this.$Message.warning('用户使用系统，那就配个角色呗？')
          return
        }
        this.currentStep = 2
      }
    },
    // 上一步
    preStep() {
      if (this.currentStep === 2) {
        this.currentStep = 1
      } else if (this.currentStep === 1) {
        this.currentStep = 0
        this.showScrollHint = true
      }
    },
    // 确定
    async ok() {
      this.btnLoading = true
      let param = this.dealParam()
      let res = await this.$API.userManagement.user.save.post(param)
      if (res.code === '01') {
        this.$Message.success('保存成功')
        this.cancel('ok')
        this.btnLoading = false
      } else {
        this.$Message.error(res.message)
        this.btnLoading = false
      }
    },
    // 组装参数
    dealParam() {
      let param = {
        ...this.model,
      }
      param.failureTime = this.model.failureTime.getTime()
      if (this.$TOOL.isNotEmpty(this.model.passWord)) {
        param.passWord = this.$TOOL.crypto.MD5(this.model.passWord)
      }
      param.roleIds = this.roleIds
      param.useSys = this.useSys ? '1' : '0'
      param.avatarFileName = this.ava['minioFileName']
      return param
    },
    // 登录账号赋值逻辑：手机号 > 用户编码
    // 更改用户编码
    changeUserCode() {
      if (this.$TOOL.isEmpty(this.model.telephone)) {
        if (this.$TOOL.isEmpty(this.model.userCode)) {
          this.model.userCode = ''
        } else {
          this.model.loginAccount = this.model.userCode
        }
      }
    },
    // 更改手机号
    changeTelephone() {
      if (this.$TOOL.isEmpty(this.model.telephone)) {
        if (this.$TOOL.isEmpty(this.model.userCode)) {
          this.model.loginAccount = ''
        } else {
          this.model.loginAccount = this.model.userCode
        }
      } else {
        this.model.loginAccount = this.model.telephone
      }
    },
    // 更改身份证号
    changeIdNumber() {
      if (this.$TOOL.isEmpty(this.model.idNumber)) {
        return
      }
      let id = this.model.idNumber
      let year = id.substring(6, 10)
      let month = id.substring(10, 12)
      let day = id.substring(12, 14)
      let birthDay = year + '-' + month + '-' + day
      this.model.birthDay = new Date(birthDay)
      this.changeBirthDay(birthDay)
    },
    // 清除身份证号
    clearIdNumber() {
      this.model.birthDay = ''
      this.model.age = ''
    },
    // 更改出生日期
    changeBirthDay(val) {
      let birthday = new Date(val)
      let today = new Date()
      let age = today.getFullYear() - birthday.getFullYear()
      if (
        today.getMonth() < birthday.getMonth() ||
        (today.getMonth() == birthday.getMonth() &&
          today.getDate() < birthday.getDate())
      ) {
        age--
      }
      if (!Number.isNaN(age)) {
        this.model.age = age
      }
    },
    // 改变角色
    changeRole(value) {
      this.roleIds = value
    },
    // 更改是否使用系统
    changeUseSys(val) {
      if (!val) {
        this.model.loginAccount = ''
      } else {
        this.model.loginAccount = this.model.telephone
          ? this.model.telephone
          : this.model.userCode
      }
    },
    // 更改密码
    changePassword() {
      if (this.model.passWord) {
        this.passWordDisabled = false
      } else {
        this.passWordDisabled = true
      }
    },
    // 上传头像之前设置进度条
    handleBeforeUpload() {
      // 进度条
      const downInterval = setInterval(() => {
        if (this.avalPercent >= 90) {
          clearInterval(downInterval)
          return
        }
        this.avalPercent += 10
      }, 500)
    },
    // 上传头像回调
    handleSuccess(res, file) {
      if (res.code == '01') {
        this.ava = { ...res.data }
        this.avalStatus = 'finished'
      }
    },
    handleView() {
      this.previewVisible = true
    },
    async handleRemove() {
      if (!this.ava.minioFileName) {
        return
      }
      // 调用接口处理已经上传minio的头像
      let res = await this.$API.userManagement.user.removeAva.get({
        fileName: this.ava.minioFileName,
      })
      if (res.code != '01') {
        this.$Message.error(res.message)
      }
      this.$refs.upload.clearFiles
      this.resetAva()
    },
    async cancel(mode) {
      this.modelIsOpen = false
      if (mode === 'close') {
        this.handleRemove()
      }
      this.reset()
      this.$emit('query')
    },
    reset() {
      if (this.currentStep === 0) {
        this.$refs.zzForm1.resetFields()
      } else if (this.currentStep === 1) {
        this.$refs.zzForm4.resetFields()
      }
      this.currentStep = 0
      this.roleIds = []
      this.useSys = true
      this.model = {
        userCode: '',
        sex: '',
        userName: '',
        idNumber: '',
        birthDay: '',
        age: '',
        telephone: '',
        email: '',
        address: '',
        school: '',
        education: '',
        major: '',
        companyCode: '',
        departmentName: '',
        jobPost: '',
        jobTitle: '',
        role: '',
        menuRight: '',
        dataRight: '',
        pendant: '',
        loginAccount: '',
        passWord: '',
        failureTime: new Date('9999-12-31'),
      }
      this.resetAva()
    },
    resetAva() {
      this.ava = {
        previewUrl: '',
        externalUrl: '',
        fileName: '',
        minioFileName: '',
      }
    },
    // 向下滚动
    scrollToTop(event) {
      if (event.target.scrollTop === 0) {
        this.showScrollHint = true
      } else {
        this.showScrollHint = false
      }
    },
  },
}
</script>

<style lang="less" scoped>
.blur-image {
  backdrop-filter: blur(30px);
}
.container {
  height: 410px;
  overflow-y: auto;
  padding: 8px 2px;
}
.scroll-hint {
  font-size: 13px;
  text-align: center;
  background: linear-gradient(to bottom, black, transparent);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 17px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-left: -80px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
